package pers.lolicer.redtidelibrary.components

import AppColor
import android.annotation.SuppressLint
import android.content.Intent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Card
import androidx.compose.material3.CardColors
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.navigation.NavController
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import pers.lolicer.redtidelibrary.R
import pers.lolicer.redtidelibrary.config.routeConfig
import pers.lolicer.redtidelibrary.utils.FileUtils

val LocalMaxWidth = staticCompositionLocalOf<Dp> { error("No maxWidth provided") }
val LocalMaxHeight = staticCompositionLocalOf<Dp> { error("No maxHeight provided") }

@SuppressLint("UnusedBoxWithConstraintsScope")
@Composable
fun TopBar(isDataSync: MutableState<Boolean>, searchFilter: MutableState<String>, navController: NavController, isContentVisible: MutableState<Boolean>){
    BoxWithConstraints {
        val constraints = topBarConstraints()
        val maxWidth = maxWidth
        val maxHeight = maxHeight

        CompositionLocalProvider(LocalMaxWidth provides maxWidth, LocalMaxHeight provides maxHeight){
            ConstraintLayout(constraints){
                SearchBar(searchFilter)
                AddButton(isDataSync)
                // SettingButtonTemp()
                SettingButton(navController, isContentVisible)
            }
        }
    }
}

// 搜索栏
@Composable
fun SearchBar(searchFilter: MutableState<String>){
    val context = LocalContext.current
    val maxWidth = LocalMaxWidth.current

    var nameState by rememberSaveable { mutableStateOf("") }
    val scope = rememberCoroutineScope()
    TextField(
        modifier = Modifier.width(maxWidth * 0.7f).layoutId("searchBar"),
        value = nameState,
        onValueChange = {
            nameState = it
            scope.launch{
                delay(50)
                searchFilter.value = it
            }

        },
        leadingIcon = {
            IconButton(
                colors = AppColor.IconButton(context),
                onClick = {},
                enabled = false
            ) {
                Icon(
                    imageVector = Icons.Default.Search,
                    contentDescription = null
                )
            }
        },
        trailingIcon = {
            if(nameState != "")
                IconButton(
                    colors = AppColor.IconButton(context),
                    onClick = {
                        nameState = ""
                        searchFilter.value = nameState
                    }
                ) {
                    Icon(
                        imageVector = Icons.Default.Clear,
                        contentDescription = "清空搜索词"
                    )
                }
        },
        colors = AppColor.TextFieldDefaults(context),
        placeholder = {
            Text(text = stringResource(R.string.placeholder_search))
        },
        singleLine = true
    )
}

// 添加书籍按钮
@Composable
fun AddButton(isDataSync: MutableState<Boolean>){
    val context = LocalContext.current
    val launcher = FileUtils().fileSelectorLauncher(context, isDataSync)
    val mimeTypes = stringArrayResource(R.array.mime_list)
    IconButton(
        modifier = Modifier.layoutId("addButton"),
        colors = AppColor.IconButton(context),
        onClick = {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "*/*"
                putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) // 支持多选
            }
            launcher.launch(intent) // 启动文件选择页面
        }
    ) {
        Icon(imageVector = Icons.Default.Add,
            contentDescription = "添加书籍"
        )
    }
}

// 设置按钮
@Composable
fun SettingButton(navController: NavController, isContentVisible: MutableState<Boolean>){
    IconButton(
        modifier = Modifier.layoutId("settingButton"),
        onClick = {
            isContentVisible.value = false
            navController.navigate(routeConfig.PAGE_SETTINGS)
        }
    ) {
        Icon(imageVector = Icons.Default.Settings,
            contentDescription = "设置"
        )
    }
}

// 约束条件
fun topBarConstraints(): ConstraintSet{
    return ConstraintSet{
        val searchBar = createRefFor("searchBar")
        val addButton = createRefFor("addButton")
        val settingButton = createRefFor("settingButton")

        constrain(searchBar){
            start.linkTo(parent.start, margin = 4.dp)
            end.linkTo(addButton.start)
            top.linkTo(parent.top)
            bottom.linkTo(parent.bottom)
        }
        constrain(addButton){
            start.linkTo(searchBar.end)
            end.linkTo(settingButton.start)
            top.linkTo(parent.top)
            bottom.linkTo(parent.bottom)
        }
        constrain(settingButton){
            start.linkTo(addButton.end)
            end.linkTo(parent.end, margin = 12.dp)
            top.linkTo(parent.top)
            bottom.linkTo(parent.bottom)
        }
    }
}